<?php
namespace app\single\controller;
use think\Db;
/**
 * #用户相关 {关于用户管理相关}
 */
class Member extends Common{
    /**
     * 用户实名认证
     * @return [type] [description]
     */
    function certification(){
        $uid=$this->user['id'];
        $data=[
            'realName'=>input('realName/s'),
            'IDNum'=>input('IDNum/s'),
        ];
        $validate=$this->validate($data,[
            'realName|真实姓名'=>'require',
            'IDNum|身份证号'=>'require|idCard',
        ]);
        if(true!==$validate){
            return json($validate,1);
        }
        $user=model($this->table)->read(['id'=>$uid],'tel,face_img,re_face_img,man_face');
        $face_img=request()->file('face_img');
        $re_face_img=request()->file('re_face_img');
        //$man_face=request()->file('man_face');

        if(!$face_img&&empty($user['face_img'])){
            //return json('请上传身份证正面照',1);
        }
        if(!$re_face_img&&empty($user['re_face_img'])){
            //return json('请上传身份证反面照',1);
        }
        // if(!$man_face&&empty($user['man_face'])){
        //     return json('请上传手执身份证照',1);
        // }

        if($face_img){
            $res=$this->loadIdNumsImg($face_img,md5("{$uid}_face_img"));
            if(!$res['success']){
                return json($res['msg'],1);
            }
            $data['face_img']=$res['msg'];
        }
        
        if($re_face_img){
            $res=$this->loadIdNumsImg($re_face_img,md5("{$uid}_re_face_img"));
            if(!$res['success']){
                return json($res['msg'],1);
            }
            $data['re_face_img']=$res['msg'];
        }
        
        // if($man_face){
        //     $res=$this->loadIdNumsImg($man_face,md5("{$uid}_man_face"));
        //     if(!$res['success']){
        //         return json($res['msg'],1);
        //     }
        //     $data['man_face']=$res['msg'];
        // }
        
        $data['is_certification']=1; //待认证
        $data['cert_remark']=''; 
        $data['cert_stime']=time(); //认证时间
        $data['id']=$uid;
        $e=model($this->table)->edit($data);
        if(empty($e)){
            return json('系统繁忙，认证信息上传失败',1);
        }
        logger('info',lang('user certification',[
            $data['realName'],
            $user['tel'],
        ]));
        return json('认证信息提交成功，请等待审核');
    }
    /**
     * 用户选择了注销账户
     * @return [type] [description]
     */
    function unregister(){
        $uid=$this->user['id'];
        model('member')->edit([
            'id'=>$uid,
            'status'=>0,
        ]);
        return json('注销成功');
    }
    /**
     * 绑定个人信息
     * @return [type] [description]
     */
    function info(){
        $uid=$this->user['id'];

        $data=[
            'wxId'=>input('wxId/s'),
            'name'=>input('name/s'),
            'sign'=>input('sign/s'),
            'sex'=>input('sex/d',0),
            'province_id'=>input('province_id/d'),
            'city_id'=>input('city_id/d'),
            'vocation_id'=>input('vocation_id/d'),
            'attr'=>json_decode(input('attr/s',''),true),
        ];
        // $validate=$this->validate($data,[
        //     'name|昵称'=>'require',
        //     'wxId|微信号'=>'require',
        //     'sign|个性签名'=>'require',
        //     'city_id|城市地区'=>'require',
        // ]);
        // if(true!==$validate){
        //     return json($validate,1);
        // }
        if(!empty($data['wxId'])){
            if(preg_match('/[^A-Za-z0-9]/', $data['wxId'])){
                return json('微信号仅允许为字母和数字的组合',1);
            }
        }
        if(!empty($data['province_id'])){
            $hasProvince=model('district')->read(['id'=>$data['province_id']],'name,extra,suffix');
            if(empty($hasProvince)){
                return json('不存在该省市',1);
            }
            $data['province']=$hasProvince['name'].$hasProvince['extra'].$hasProvince['suffix'];
        }
        if(!empty($data['city_id'])){
            $hasCity=model('district')->read(['id'=>$data['city_id']],'name,extra,suffix');
            if(empty($hasCity)){
                return json('不存在该城市',1);
            }
            $data['city']=$hasCity['name'].$hasCity['suffix'];
        }
        if(!empty($data['vocation_id'])){
            $hasVocation=model('vocation')->read(['id'=>$data['vocation_id']],'name');
            if(empty($hasVocation)){
                return json('不存在该职业',1);
            }
            $data['vocation']=$hasVocation['name'];
        }
        $attr=[];
        if(!empty($data['attr'])){
            $attr=$data['attr'];
            unset($data['attr']);
            $data['attr_str']=','.implode(',', $attr);
        }
        $user=model('member')->read(['id'=>$uid],'id,name,city_id,head_img,qrcode');
        
        // 上传头像
        $head_img=request()->file('head_img');
        // if(empty($user['head_img'])&&!$head_img){
        //     return json('请上传头像',1);
        // }
        if($head_img){
            $h=$this->loadHeadImg($head_img);
            if(!$h['success']){
                return json($h['msg'],1);
            }
            $data['head_img']=$h['msg'];
        }
        // 上传微信二维码
        $qrcode=request()->file('qrcode');
        if($qrcode){
            $q=$this->loadHeadImg($qrcode);
            if(!$q['success']){
                return json($q['msg'],1);
            }
            $data['qrcode']=$q['msg'];
        }
        
        $data['id']=$uid;
        $data['is_perfect']=1;
        $data['perfect_time']=time();
        foreach ($data as $k => $v) {
            if(empty($v)){
                unset($data[$k]);
            }
        }
        $edit=model($this->table)->edit($data);
        if(empty($edit)){
            return json('系统繁忙，更新失败',1);
        }
        if(!empty($user['head_img'])){
            $this->deleteUploadFile($user['head_img']);
        }
        if(!empty($user['qrcode'])){
            $this->deleteUploadFile($user['qrcode']);
        }
        if(!empty($attr)){
            model('member_attr')->del(['uid'=>$uid]);
            $a=[];
            foreach ($attr as $v) {
                $a[]=['uid'=>$uid,'attr_id'=>$v];
            }
            model('member_attr')->add($a);
        }
        // $hasCard=model('Testweixin')->where(['uid'=>$uid])->count();
        // if(!$hasCard){
        //     controller('Testweixin')->release($data['wxId'],1,$data['sign'],null,$data['city_id'],$attr);
        // }
        return json('更新个人信息成功');
    }
    /**
     * 绑定支付宝
     * @return [type] [description]
     */
    function bingAlipay($type='alipay'){
        $data=[
            'alipay_realname'=>input('alipay_realname/s',''),
            'alipay'=>input('alipay/s',''),
        ];
        $v=[
            'alipay_realname|姓名'=>'require',
            'alipay|支付宝账户'=>'require',
        ];
        if($type=='weixin'){
            $data=[
                'weixin_realname'=>input('weixin_realname/s',''),
                'weixin'=>input('weixin/s',''),
            ];
            $v=[
                'weixin_realname|姓名'=>'require',
                'weixin|微信号'=>'require',
            ];
        }elseif($type=='bank'){
            $data=[
                'bank_realname'=>input('bank_realname/s',''),
                'bank_name'=>input('bank_name/s',''),
                'bank_no'=>input('bank_no/s',''),
            ];
            if(!preg_match('/^([1-9]{1})(\d{14}|\d{18})$/', $data['bank_no'])){
                //return json('银行卡号不正确',1);
            }
            $v=[
                'bank_realname|开户名'=>'require',
                'bank_name|银行名称'=>'require',
                'bank_no|银行卡号'=>'require',
            ];
        }
        $validate=$this->validate($data,$v);
        if(true!==$validate){
            return json($validate,1);
        }
        
        $data['id']=$this->user['id'];
        $edit=model($this->table)->edit($data);
        if($edit){
            return json('绑定成功',0,$data);
        }
        return json('系统繁忙，绑定失败',1);
    }

    /**
     * 提现记录
     * @return [type] [description]
     */
    function cash(){
        $list=model('cash')->readAll(['uid'=>$this->user['id']],true,['order'=>'s_time desc']);
        foreach ($list as $k => $v) {
            $list[$k]['money']=$v['raw_money'];
        }
        return json('',0,$list);
    }
    /**
     * 用户提现
     * @param  double $money 提现金额
     * @param  string $type  提现类型 alipay、weixin、bank
     * @return [type]         [description]
     */
    function withdrawCash($money=0,$type='alipay'){
        $uid=$this->user['id'];
        $user=model('member')->read(['id'=>$uid],'id,tel,alipay,alipay_realname,weixin_realname,bank_realname,weixin,bank_name,bank_no');

        if($type=='alipay'&&(empty($user['alipay_realname'])||empty($user['alipay']))){
            return json('请先绑定支付宝',1);
        }
        if($type=='weixin'&&(empty($user['weixin_realname'])||empty($user['weixin']))){
            return json('请先绑定提现微信号',1);
        }
        if($type=='bank'&&(empty($user['bank_name'])||empty($user['bank_no']))){
            return json('请先绑定银行卡号',1);
        }
        $hasCount=model('cash')->where(['uid'=>$uid,'state'=>0])->count();
        if($hasCount){
            return json('请先等待上一笔审核完成',1);
        }
        if($money<10){
            return json('每次最低提现金额10元起',1);
        }
        if($money%10>0){
            return json('仅允许提取10的整数倍金额',1);
        }
        if($money>10000){
            return json('每次最高提现金额10000元',1);
        }
        $nowTime=strtotime(date('Ymd'));
        $c=model('cash')->where([
            'uid'=>$user['id'],
            's_time'=>[
                's_time',
                'between',
                [$nowTime,$nowTime+86400]
            ]
        ])->count();
        if($c>=3){
            return json('每日最多可以提现3次',1);
        }
        $_umoney=model('member')->read(['id'=>$user['id']],'money');
        if($_umoney['money']<$money){
            return json('您当前的余额不足，无法提现',1);
        }
        $realname=$user['alipay_realname'];
        if($type=='weixin'){
            $realname=$user['weixin_realname'];
        }elseif($type=='bank'){
            $realname=$user['bank_realname'];
        }
        $fee=3; //平台手续费 每次3元
        // 本月已经提现金额
        $moneyTime=strtotime(date('Y-m'));
        $amoney=model('cash')->where([
            'uid'=>$uid,
            'state'=>1,
            's_time'=>['s_time','>=',$moneyTime]
        ])->sum('raw_money');
        // 计算个人所得税
        $tax=tax($amoney,$money);
        $result=true;
        $data=[];
        Db::startTrans();
        try {
            $module=model('artmodule')->read(['name'=>request()->module()],'id');
            $data=[
                'uid'=>$user['id'],
                'tel'=>$user['tel'],
                'money'=>sprintf("%.2f", $tax[1]-$fee),
                'raw_money'=>$money,
                'type'=>$type,
                'fee'=>$fee,
                'amoney'=>$amoney+$money,
                'tax'=>$tax[0],
                'realname'=>$realname,
                'module_id'=>$module['id'],
                's_time'=>time(),
                'number'=>model('cash')->number(),
            ];
            if($type=='alipay'){
                $data['bank_no']=$user['alipay'];
            }elseif($type=='weixin'){
                $data['bank_no']=$user['weixin'];
            }else{
                $data['bank_no']=$user['bank_no'];
                $data['bank_name']=$user['bank_name'];
            }
            $log=model('cash')->add($data);
            if(empty($log)){
                exception('提现失败，请稍后再试');
            }
            $inc=model('member')->where([
                'id'=>$user['id'],
                'money'=>['money','>=',$money]
            ])->setDec('money',$money);
            if(!$inc){
                exception('余额不足或者系统繁忙，提现失败。');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result=$e->getMessage();
        }
        if(true!==$result){
            return json($result,1);
        }
        $msg='提现申请成功，等待确认';
        if($data['type']==='alipay'){
            // 人工审核
            // $_data=[
            //     'out_biz_no'=>$data['number'],
            //     'payee_account'=>$data['bank_no'],
            //     'amount'=>$data['money'],
            // ];
            // $res=alipayTransfer($_data);
            // $res=$res['alipay_fund_trans_toaccount_transfer_response'];
            
            // if($res['code']==10000){
            //     model('cash')->withdrawCash($log['id'],$uid,$data['money'],'支付宝转账',$res['order_id']);
            //     $msg='提现成功!';
            // } 
        }
        // 提现提醒
        $this->setWithdrawCashSysMessage($data);
        $money=model('member')->read(['id'=>$user['id']],'money');
        return json($msg,0,['money'=>$money['money']]);
    }
    private function setWithdrawCashSysMessage($data){
        //$str="【提现消息】用户%s(%s)于%s通过%s申请提现%s元。<a href='%s'>点击前往处理</a>";
        $message=lang('withdraw cash system message',[
            $data['realname'],
            $data['tel'],
            date('Y-m-d H:i:s',$data['s_time']),
            lang($data['type']),
            $data['raw_money'],
            url('admin/cash/index',['keyword'=>$data['tel']]),
        ]);
        $uid=config('auth.sys_message_id');
        logger('info',lang('user withdraw',[
            $data['realname'],
            $data['tel'],
            lang($data['type']),
            $data['raw_money'],
        ]));
        return model('Customer')->push($uid,$message);
    }
}